<template>
  <div @click="launch">
    <wx-open-launch-app :id="id"
                        class="launch-btn"
                        :appid="appId"
                        :extinfo="extinfoStr"
    >
      <script type="text/wxtag-template">
        <style>.btn {height: 96px;}</style>
        <div class="btn">打开app</div>
      </script>
    </wx-open-launch-app>
  </div>
</template>

<script>
let idIndex = 0
export default {
  name: 'LaunchButton',
  props: {
    extinfo: {
      type: Object,
      default: () => ({})
    },
    config: {
      type: Object,
      default: () => ({
        appId: '',
        appUrl: '',
        wxVersion: ''
      })
    }
  },
  emits: ['fail', 'success'],
  data() {
    idIndex++
    return {
      id: `wxopenLanchAppId${idIndex}`,
      appId: this.config.appId,
      extinfoStr: '',
    }
  },
  watch: {
    extinfo: {
      handler(n) {
        this.extinfoStr = JSON.stringify(n)
      },
      immediate: true
    }
  },
  mounted() {
    const btn = document.getElementById(this.id)
    btn.addEventListener('launch', e => {
      this.$emit('success', e)
    })
    btn.addEventListener('error', e => {
      this.$emit('fail', e)
      this.redirectToApp()
    })
  },
  methods: {
    redirectToApp() {
      setTimeout(() => {
        window.location.href = this.config.appUrl
      }, 400)
    },
    launch() {
      this.$emit('success', true)
      // 微信版本号大于 7.0.12 开放标签才可进行 唤醒 app 跳转
      let enable = false
      if (this.config.wxVersion) {
        const v = this.config.wxVersion.split('.')
        if (v[0] >= 7) {
          if (v[1] >= 0) {
            if (v[2] >= 12) {
              enable = true
            }
          }
        }
      }
      if (!enable) {
        this.redirectToApp()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .launch-btn {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  opacity: 0;
  // background: red;
}
</style>
